#include "chatservice.h"
#include "global.h"
#include <QUrlQuery>

ChatService::ChatService(QString id,QString identity)
    : QObject(),
    Id(id),
    Identity(identity)

{

}

void ChatService::slot_initWebsocket()
{
    m_webSocket = new QWebSocket();
    // 当WebSocket成功连接到服务器时，会触发QWebSocket::connected信号
    connect(m_webSocket, &QWebSocket::connected, this, &ChatService::onConnected);
    // 当WebSocket接收到文本消息时，会触发QWebSocket::textMessageReceived信号
    connect(m_webSocket, &QWebSocket::textMessageReceived, this, &ChatService::onTextMessageReceived);

    // 当WebSocket与服务器的连接断开时，会触发QWebSocket::disconnected信号
    connect(m_webSocket, &QWebSocket::disconnected, this, &ChatService::onDisconnected);
    // 设置请求 URL 并携带 userId 参数

    // 使用 qOverload 明确指定 error 信号的重载版本
    connect(m_webSocket, qOverload<QAbstractSocket::SocketError>(&QWebSocket::error), [this](QAbstractSocket::SocketError error) {
        qDebug() << "WebSocket connection error:" << m_webSocket->errorString();
    });
    QUrlQuery query;
    query.addQueryItem("Id",Id);
    query.addQueryItem("Identity",Identity);
    QUrl fullUrl("ws://localhost:8080/startChatService");
    fullUrl.setQuery(query);
    m_webSocket->open(fullUrl);
}

void ChatService::slot_sendImageMsg(QByteArray imageMsg)
{
    m_webSocket->sendBinaryMessage(imageMsg);
}

void ChatService::slot_sendTextMsg(QString msg)
{
    m_webSocket->sendTextMessage(msg);
}

void ChatService::onConnected()
{
    emit sig_Connected();
}

void ChatService::onTextMessageReceived(const QString message)
{
    emit sig_TextMessageReceived(message);

}



void ChatService::onDisconnected()
{
    emit sig_Disconnected();
}


